<template>
  <div class="swiper-nav-container">
    <div class="swiper-wrapper">
      <div
        class="swiper-slide"
        v-for="(item, index) in data"
        :key="index"
        :class="[slideClass, { [slideActiveClass]: modelValue === index }]"
      >
        <slot :item="item" />
      </div>
    </div>
  </div>
</template>

<script>
import Swiper from 'swiper/js/swiper.js';
import 'swiper/css/swiper.css';

export default {
  name: 'NavSwiper',
  data() {
    return {
      mySwiper: null,
      swiperOption: {
        initialSlide: this.value,
        slidesPerView: 'auto',
        centeredSlides: true,
        centeredSlidesBounds: true,
        freeMode: true,
        resizeObserver: false,
        updateOnWindowResize: false,
        on: {
          tap: () => {
            this.$emit('update:modelValue', this.mySwiper.clickedIndex);
          },
        },
      },
    };
  },
  props: {
    modelValue: {
      type: [Number, String],
    },
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    slideClass: String,
    slideActiveClass: String,
  },
  methods: {
    initSwiper() {
      this.mySwiper = new Swiper('.swiper-nav-container', this.swiperOption);
    },
  },
  mounted() {
    this.initSwiper();
    window.addEventListener('resize', () => {
      this.$nextTick(() => {
        this.mySwiper.$el[0].scrollTo({
          left: -200,
        });
      });
    });
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.mySwiper && this.mySwiper.slideTo(val);
        });
      },
    },
  },
  components: {},
};
</script>
<style lang="scss">
.swiper-nav-container{
 overflow-x: hidden;
 overflow-y: auto;
}
</style>
